<script lang="ts">
  import { onMount } from 'svelte';
  import * as echarts from 'echarts';

  interface DeviceItem {
    color: string;
    name: string;
    count: number;
    percentage: string;
  }

  export let pageData: Record<string, any> = {};
  const deviceList: DeviceItem[] = [
    {
      color: '#0A5DA2',
      name: '全部设备',
      count: 6,
      percentage: '100%'
    },
    {
      color: '#91cc75',
      name: '激活设备',
      count: 6,
      percentage: '100%'
    },
    {
      color: '#fac858',
      name: '激活在线',
      count: 6,
      percentage: '100%'
    },
    {
      color: '#ee6666',
      name: '激活离线',
      count: 0,
      percentage: '0%'
    }
  ];

  let charts = [];
  let scale = 1;

  // 创建图表配置的函数
  const createChartOption = (device: DeviceItem) => {
    const percentValue = parseInt(device.percentage);
    
    return {
      grid: {
        left: 0,
        right: 0,
        top: 0,
        bottom: 0
      },
      xAxis: {
        type: 'value',
        max: 100,
        show: false
      },
      yAxis: {
        type: 'category',
        data: [device.name],
        show: false
      },
      series: [
        {
          type: 'bar',
          data: [percentValue],
          barWidth: '100%',
          showBackground: false,
          backgroundStyle: {
            // color: 'rgba(255, 255, 255, 0.1)'
          },
          itemStyle: {
            color: device.color,
            borderRadius: 10
          },
          label: {
            show: false,
            position: 'inside',
            formatter: '{c}%',
            fontSize: '1.2rem',
            fontWeight: 'bold',
            color: '#ffffff',
            align: 'center',
            verticalAlign: 'middle'
          }
        }
      ]
    };
  };

  // 更新图表数据的函数
  const updateCharts = () => {
    charts.forEach((chart, index) => {
      if (chart && deviceList[index]) {
        const option = createChartOption(deviceList[index]);
        chart.setOption(option);
      }
    });
  };

  onMount(() => {
    // 为每个设备创建一个进度条图表
    deviceList.forEach((device, index) => {
      const chartDom = document.getElementById(`progressBar${index}`);
      if (chartDom) {
        const chart = echarts.init(chartDom);
        const option = createChartOption(device);
        chart.setOption(option);
        charts.push(chart);
      }
    });

    // 窗口大小变化时重新调整图表大小
    const handleResize = () => {
      charts.forEach(chart => {
        if (chart) {
          chart.resize();
        }
      });
    };
    
    window.addEventListener('resize', handleResize);
    
    return () => {
      window.removeEventListener('resize', handleResize);
      charts.forEach(chart => {
        if (chart) {
          chart.dispose();
        }
      });
    };
  });

  // 响应式更新数据
  $: if (pageData) {
    if (innerWidth < 1920) {
      scale = 0.8;
    } else {
      scale = 1;
    }
    
    // 更新设备数量
    deviceList[0].count = pageData.deviceCount || 0;
    deviceList[1].count = pageData.activateDeviceCount || 0;
    deviceList[2].count = pageData.activateOnlineDeviceCount || 0;
    deviceList[3].count = pageData.activateOfflineDeviceCount || 0;
    
    // 计算百分比，避免除零错误
    const totalCount = deviceList[0].count;
    if (totalCount > 0) {
      deviceList[0].percentage = '100%';
      deviceList[1].percentage = `${((deviceList[1].count / totalCount) * 100).toFixed(2)}%`;
      deviceList[2].percentage = `${((deviceList[2].count / totalCount) * 100).toFixed(2)}%`;
      deviceList[3].percentage = `${((deviceList[3].count / totalCount) * 100).toFixed(2)}%`;
    } else {
      deviceList[0].percentage = '0%';
      deviceList[1].percentage = '0%';
      deviceList[2].percentage = '0%';
      deviceList[3].percentage = '0%';
    }
    
    // 更新图表
    updateCharts();
  }
</script>

<div class="flex flex-col gap-2 w-full px-4 h-[22%] progress-bar">
  {#each deviceList as device, i}
    <div class="flex items-center">
      <span class="text-base text-white/90 w-28">{device.name}</span>
      <div class="border-4 relative" style="transform: scale(1,{scale}); transform-origin: center center; border-color:{device.color}; width: calc(100% - 100px); height: 30px;border-radius: 30px; padding: 4px; display: flex; align-items: center; flex-direction: column; justify-content: center;">
        <div class="absolute z-10 top-[50%] left-[50%] -translate-x-1/2 -translate-y-1/2  rounded-full " style="color:white; font-size:12px; font-weight:bold; text-align:center;">
        {device.percentage}
        </div>
        <div style=" transform-origin: center center; width: 100%; height: 14px;" id="progressBar{i}"></div>
    </div>
      <div class="text-base text-white/90 ml-3 w-[44px] text-right">{device.count}</div>
    </div>
  {/each}
</div> 

<style>
  .progress-bar {
     font-size: 1.2rem !important;
  }
</style>
